<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="新闻标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入新闻标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="新闻类型" prop="typeId">
        <el-cascader
          :options="newsTypeDataArray"
          v-model="queryNewsTypeIdTree"
          ref="queryNewsTypeCascader"
          @change="handleQueryCascaderChange"
          :props="{ value:'value', label:'name', children: 'children' , checkStrictly: true }"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="新闻状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择新闻状态"
        >
          <el-option label="全部" value=""/>
          <el-option label="正常" selected value="NORMAL"/>
          <el-option label="延迟发布" selected value="DELAY_PUBLISH"/>
          <el-option label="发布" selected value="PUBLISH"/>
          <el-option label="删除" value="DELETED"/>
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-input
          v-model="queryParams.source"
          placeholder="请输入来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['heima:news:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="queryParams.status !=='NORMAL'"
          @click="handlePublish"
          v-hasPermi="['heima:news:publish']"
        >发布</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="queryParams.status !=='NORMAL'"
          @click="handleDelete"
          v-hasPermi="['heima:news:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="新闻ID" align="center" prop="newsId" />
      <el-table-column label="新闻标题" align="center" prop="title" />
      <el-table-column label="新闻类型" align="center" prop="typeId" :formatter="formatNewsType" />
      <el-table-column label="来源" align="center" prop="source" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['heima:news:edit']"
            :disabled="scope.row.status === '发布'||scope.row.status === '延迟发布'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlePublish(scope.row)"
            v-hasPermi="['heima:news:publish']"
            :disabled="scope.row.status !== '正常'"
          >发布</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.status !== '正常'"
            v-hasPermi="['heima:news:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改新闻对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="form.title" required placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="新闻类型" prop="typeId">
          <el-cascader
            :options="newsTypeDataArray"
            v-model="newsTypeIdTree"
            ref="newsTypeCascader"
            @change="handleCascaderChange"
            :props="{ value:'value', label:'name', children: 'children' , checkStrictly: true }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="新闻内容">
          <editor v-model="form.content" required :min-height="192"/>
        </el-form-item>
        <el-form-item label="新闻状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择新闻状态"
            required
          >
            <el-option label="正常" selected value="正常"/>
            <el-option label="删除" value="删除"/>
          </el-select>

        </el-form-item>
        <el-form-item label="延时发布" prop="delayTime" >
          <el-input-number v-model="form.delayTime" :min="0" :max="100" :step="1"></el-input-number>
          （分钟）
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNews, getNews, delNews, addNews, updateNews, publishNews } from "@/api/heima/news";
import { getAllNewsType } from "@/api/heima/newsType";

export default {
  name: "News",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻表格数据
      newsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        typeId: null,
        searchValue: null,
        source: null,
        status: 'NORMAL',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: '请输入新闻类型', trigger: 'blur' }
        ]
      },
      //整棵新闻类型树
      newsTypeDataArray: [],
      // 新闻分类层级id
      newsTypeIdTree: [],
      // 查询中的新闻分类层级id
      queryNewsTypeIdTree: []

    };
  },
  created() {
    this.getList();
    //构建新闻类型
    this.buildNewsTypeTree();

  },
  methods: {
    /** 查询新闻列表 */
    getList() {
      this.loading = true;
      listNews(this.queryParams).then(response => {
        this.newsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        newsId: null,
        title: null,
        typeId: null,
        content: null,
        delayTime: 0,
        source: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        status: null,
        remark: null
      };
      this.newsTypeIdTree = [];

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      //将新闻类型迭代获取所有子类id后再查询
      if (this.queryNewsTypeIdTree.length > 0 && this.queryNewsTypeIdTree.length < 3) {
        let typeIdArrays = [];
        if (this.queryNewsTypeIdTree.length === 1) {
          //一级分类；获取其二级、三级分类id
          let typeId = this.queryNewsTypeIdTree[0];
          typeIdArrays.push(typeId);
          let children = this.newsTypeDataArray.find(item => item.value === typeId).children;
          for (let j = 0; j < children.length; j++) {
            typeIdArrays.push(children[j].value);
            if (children[j].children.length > 0) {
              let childrenChildren = children[j].children;
              for (let k = 0; k < childrenChildren.length; k++) {
                typeIdArrays.push(childrenChildren[k].value);
              }
            }
          }
        } else if (this.queryNewsTypeIdTree.length === 2) {
          //二级分类；获取其三级分类id
          let typeId = this.queryNewsTypeIdTree[1];
          typeIdArrays.push(typeId);
          for (let i = 0; i < this.newsTypeDataArray.length; i++) {
            let children = this.newsTypeDataArray[i].children;
            for (let j = 0; j < children.length; j++) {
              if (children[j].value === typeId) {
                let childrenChildren = children[j].children;
                for (let k = 0; k < childrenChildren.length; k++) {
                  typeIdArrays.push(childrenChildren[k].value);
                }
              }
            }
          }
        }
        this.queryParams.searchValue = typeIdArrays.join(',');
      }

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryNewsTypeIdTree = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.newsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加新闻";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const newsId = row.newsId || this.ids
      getNews(newsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改新闻";

        //回显新闻分类
        if (this.form.typeId !== null) {
          let typeId = this.form.typeId;
          for (const firstTreeNode of this.newsTypeDataArray) {
            for (const secondTreeNode of firstTreeNode.children) {
              for (const thirdTreeNode of secondTreeNode.children) {
                if (thirdTreeNode.value === typeId) {
                  this.newsTypeIdTree.push(firstTreeNode.value, secondTreeNode.value, typeId);
                  break;
                }
              }
            }
          }
        }

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.newsId != null) {
            updateNews(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNews(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 发布按钮操作 */
    handlePublish(row) {
      const newsIds = row.newsId || this.ids;
      this.$modal.confirm('是否确认发布新闻编号为"' + newsIds + '"的数据项？').then(function() {
        return publishNews(newsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发布成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const newsIds = row.newsId || this.ids;
      this.$modal.confirm('是否确认删除新闻编号为"' + newsIds + '"的数据项？').then(function() {
        return delNews(newsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 处理新闻类型的中文显示 */
    formatNewsType(row, column) {
      let typeId = row.typeId;

      //从新闻分类树中获取新闻类型中文
      for (const firstTreeNode of this.newsTypeDataArray) {
        if (firstTreeNode.value === typeId) {
          return firstTreeNode.name;
        }
        for (const secondTreeNode of firstTreeNode.children) {
          if (secondTreeNode.value === typeId) {
            return secondTreeNode.name;
          }
          for (const thirdTreeNode of secondTreeNode.children) {
            if (thirdTreeNode.value === typeId) {
              return thirdTreeNode.name;
            }
          }
        }
      }
    },
    /** 选择新闻类型 */
    handleCascaderChange(newTypeIds){
      if (newTypeIds.length >= 3) {
        this.form.typeId=newTypeIds[newTypeIds.length-1];
        //隐藏下拉
        this.$refs.newsTypeCascader.toggleDropDownVisible();
      }
    },
    /** 查询中的选择新闻类型 */
    handleQueryCascaderChange(newTypeIds){
      if (newTypeIds.length > 0 && newTypeIds.length <= 3) {
        this.queryParams.searchValue=newTypeIds[newTypeIds.length-1];
        this.$refs.queryNewsTypeCascader.toggleDropDownVisible();
      }

    },
    /** 构建新闻类型树对象 */
    buildNewsTypeTree() {
      getAllNewsType().then(response => {
        const dataList = response;

        // 使用Map存储每个节点，方便查找父节点
        const nodeMap = new Map();

        // 遍历数据列表，创建节点并添加到Map中
        for (const data of dataList) {
          const typeId = data.typeId;
          const typeName = data.typeName;
          const parentId = data.parentId;

          const node = { name: typeName, value: typeId, children: [] };
          nodeMap.set(typeId, node);

          if (parentId === 0) {
            // 根节点
            this.newsTypeDataArray.push(node);
          } else {
            // 非根节点，添加到父节点的子节点列表中
            const parent = nodeMap.get(parentId);
            parent.children.push(node);
          }
        }

      });

    }

  }
};
</script>
